type CachedKey = string | number;
type Timer = ReturnType<typeof setTimeout>;
export interface CachedData<TData = any, TRunArgs = any> {
  data: TData;
  runArgs: TRunArgs;
  time: number;
  timer: Timer | undefined;
}

const cacheMap = new Map<CachedKey, CachedData>();

export function setCache(cacheKey: CachedKey, cacheTime: number, cachedData: CachedData) {
  // cacheMap.set(cacheKey, cachedData);
  const originCacheData = cacheMap.get(cacheKey);
  if (originCacheData) {
    clearTimeout(originCacheData.timer);
  }
  cacheMap.set(cacheKey, {
    ...cachedData,
    timer: setTimeout(() => {
      //主动删除，释放内存
      clearCache(cacheKey);
    }, cacheTime),
  });
}

export function getCache(cacheKey: CachedKey) {
  return cacheMap.get(cacheKey);
}

export function clearCache(cacheKey: CachedKey | CachedKey[]) {
  if (cacheKey) {
    const cackeKeyArray = Array.isArray(cacheKey) ? cacheKey : [cacheKey];
    cackeKeyArray.forEach((key) => cacheMap.delete(key));
  } else {
    cacheMap.clear();
  }
}